//
//  NearbyViewController.m
//  安好
//
//  Created by lianchuang on 14-11-10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "NearbyViewController.h"
#import "FriendCell.h"
#import "EncyHospitalCell.h"
#import "DrugNearStoreCell.h"
#import "DocInfoViewController.h"
#import "CustomAnnotationView.h"
#import "RegexKitLite.h"
#import "NearbyPathViewController.h"
#import "FirendDetailViewController.h"
#import "PopoverView.h"
#import "UIImageView+AFNetworking.h"
#import "DoctorDetailViewController.h"
@interface NearbyViewController ()<CustomAnnotationViewDelegate,UIActionSheetDelegate,CallActionDelegate,UIActionSheetDelegate>

@end

@implementation NearbyViewController
{
    UIButton *rightButtonMore;
    UIButton *hosrightButton;
    UIButton *storerightButton;
    BOOL showHosList;
    BOOL showStoreList;
    AMapPOI *p;
    CLLocationCoordinate2D tolocation;
    NSMutableArray *storeTelArray;
    
    NSArray *telArray;
    //所有附近医院的气泡
    NSMutableArray *flagHospArray;
    //所有附近药店的气泡
    NSMutableArray *flagStoreArray;
    NSInteger indexSelected;
    
    NSString *cityName;
    //附近的人筛选数组
    NSArray *tempArray;
    PopoverView *pop;
    BOOL success;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [pop dismiss:YES];
    self.locationger = nil;
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.personNearbyArray=[[NSMutableArray alloc]init];
    self.hospitalNearbyArray=[[NSMutableArray alloc]init];
    self.storeNearbyArray=[[NSMutableArray alloc]init];
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    self.navigationItem.title=@"附近";
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    CGFloat height;
    if (kScreenWidth==414) {
        height=9;
    }else{
        height=0;
    }
    
    self.mapview=[[MAMapView alloc]initWithFrame:CGRectMake(0, self.personLine.bottom-4, kScreenWidth, CGRectGetHeight(self.view.frame)-44-height)];
    self.mapview.delegate=self;
    [self.view addSubview:self.mapview];
    self.mapview.hidden=NO;
    
    self.nearPersonTableview.frame=CGRectMake(0, self.perseonSender.bottom-4, kScreenWidth,kScreenHeight-44 -height- 64);
    self.nearHospital.frame=CGRectMake(0, 44+height-4, kScreenWidth, kScreenHeight-44-height - 64);
    self.nearStore.frame=CGRectMake(0, 44+height-4, kScreenWidth, kScreenHeight-44-height - 64);
    self.nearPersonTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.nearHospital.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.nearStore.separatorStyle=UITableViewCellSeparatorStyleNone;

    self.nearPersonTableview.hidden=YES;
    self.nearPersonTableview.dataSource=self;
    self.nearHospital.dataSource=self;
    self.nearStore.dataSource=self;
    self.nearPersonTableview.delegate=self;
    self.nearHospital.delegate=self;
    self.nearStore.delegate=self;
    self.perseonSender.titleLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];
    self.hospitalSender.titleLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];
    self.storeSender.titleLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];

    
    
    [self.hospitalSender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal];
    [self setnarBar];
    [self creatlocation];
    
    self.hosPage=0;
    self.storePage=0;
    
    rightButtonMore = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButtonMore.frame = CGRectMake(0,0,23, 23);

    [rightButtonMore setImage:[UIImage imageNamed:@"公用_更多@2x.png"] forState:UIControlStateNormal];
    [rightButtonMore addTarget:self action:@selector(showListView:) forControlEvents:UIControlEventTouchUpInside];
    
    hosrightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [hosrightButton setTitle:@"列表" forState:UIControlStateNormal];
    hosrightButton.titleLabel.font=[UIFont systemFontOfSize:15];
    [hosrightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];

    hosrightButton.tag=10;
    [hosrightButton addTarget:self action:@selector(rightButtonAddCircleClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    storerightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [storerightButton setTitle:@"列表" forState:UIControlStateNormal];
    [storerightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    storerightButton.titleLabel.font=[UIFont systemFontOfSize:15];
    storerightButton.tag=11;
    [storerightButton addTarget:self action:@selector(rightButtonAddCircleClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:hosrightButton];
    

    showHosList=NO;
    showStoreList=NO;
    indexSelected=1;
    storeTelArray=[[NSMutableArray alloc]init];
    flagHospArray=[[NSMutableArray alloc]init];
    flagStoreArray=[[NSMutableArray alloc]init];
    
    
    tempArray=[[NSArray alloc]init];
}
- (void)creatlocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationger = [[CLLocationManager alloc] init];
        self.locationger.distanceFilter = 1000;
        self.locationger.delegate=self;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
        
        if (IOS8_OR_LATER) {
            [self.locationger requestAlwaysAuthorization];
        }
#endif
        [self.locationger startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        casekCLAuthorizationStatusNotDetermined:
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//            if ([self.locationger respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
//                [self.locationger requestWhenInUseAuthorization];
//            }
//#endif
            break;
        default:
            break;
    }
}

//定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    success=YES;
    manager.delegate=nil;
    [self.locationger stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    self.latitude = [NSString stringWithFormat:@"%f",coor.latitude] ;
    self.longitude = [NSString stringWithFormat:@"%f",coor.longitude];
    MACoordinateSpan span = MACoordinateSpanMake(0.1, 0.1);
    MACoordinateRegion region = MACoordinateRegionMake(coor, span);
    [self.mapview setRegion:region animated:YES];
    self.mapview.showsUserLocation=YES;
//    [self postUserLatAndLongtude];
    [self loadNearHospitalData];
}

/**
 *  上传用户经纬度
 */
- (void)postUserLatAndLongtude
{
    NSString * postURL = [NSString stringWithFormat:@"%@user/lnglat/",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"lat":self.latitude,
                                 @"lng":self.longitude,
                                 @"gender":[userdefault valueForKey:[NSString stringWithFormat:@"%@gender",userModel.uid]],
                                 @"status":@"3",
                                 };
    [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            [self loadDataWithType:@"3"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (void)loadDataWithType:(NSString *)type
{
    [self showActionView];
    
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *statusType=[userdefault valueForKey:[NSString stringWithFormat:@"AllNear%@",userModel.uid]];
    NSString *status;
    if ([statusType isEqualToString:@"3"])
    {
        if ([[userdefault valueForKey:[NSString stringWithFormat:@"AnNear%@",userModel.uid]]isEqualToString:@"1"]&&[[userdefault valueForKey:[NSString stringWithFormat:@"DoctionNear%@",userModel.uid]]isEqualToString:@"2"]) {
            status=@"3";
        }else if ([[userdefault valueForKey:[NSString stringWithFormat:@"AnNear%@",userModel.uid]]isEqualToString:@"1"]&&[[userdefault valueForKey:[NSString stringWithFormat:@"DoctionNear%@",userModel.uid]]isEqualToString:@"0"])
        {
            status=@"1";
        }else if ([[userdefault valueForKey:[NSString stringWithFormat:@"AnNear%@",userModel.uid]]isEqualToString:@"0"]&&[[userdefault valueForKey:[NSString stringWithFormat:@"DoctionNear%@",userModel.uid]]isEqualToString:@"2"])
        {
            status=@"2";
        }else
        {
            status=@"4";
        }
    }else
    {
        status=@"4";
    }
    NSString * postURL = [NSString stringWithFormat:@"%@user/near/",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"lat":self.latitude,
                                 @"lng":self.longitude,
                                 @"type":type,
                                 //可见？
                                 @"status":status,
                                 };
    [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            self.nearPersonTableview.hidden=NO;
            tempArray=[responseObject valueForKey:@"data"];
            self.personNearbyArray=[NSMutableArray arrayWithArray:[responseObject valueForKey:@"data"]];
            [self.nearPersonTableview reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self shouLabel:@"暂无数据"];
    }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请先打开GPS" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alert show];
    [self showCustomHudSingleLine:@"请先打开GPS"];
}

- (void)setnarBar
{
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
}
#pragma  mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.nearPersonTableview]) {
        return self.personNearbyArray.count;
    }
    else if([tableView isEqual:self.nearHospital])
    {
        return self.hospitalNearbyArray.count;
    }
    else
    {
        return self.storeNearbyArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if ([tableView isEqual:self.nearPersonTableview]) {
        static NSString * CellIdentifier1 = @"FriendCell";
        FriendCell * personCell = (FriendCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        personCell.selectionStyle=UITableViewCellSelectionStyleNone;
        if (self.personNearbyArray.count>0) {
            if (!personCell) {
                if (kScreenWidth==414) {
                    personCell = [[[NSBundle mainBundle] loadNibNamed:@"FriendCell" owner:self options:nil] lastObject];
                }
                else{
                    personCell = [[[NSBundle mainBundle] loadNibNamed:@"FriendCell" owner:self options:nil] objectAtIndex:0];
                }
            }
            if ([[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"avatar"] isEqualToString:@""])
            {
            }
            else
            {
                [personCell.userImage setImageWithURL:[NSURL URLWithString:[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"avatar"]]placeholderImage:[UIImage imageNamed:@"默认头像"]];
                
            }
            personCell.userImage.layer.cornerRadius=3;
            personCell.userImage.layer.masksToBounds=YES;
            if ([[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"username"] isEqual:[NSNull null]]) {
            }
            else
            {
                personCell.userLabel.text=[[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"username"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                
                CGSize size=[self autolayoutText:personCell.userLabel.text WithTextLabel:personCell.userLabel WithWidth:125];
                if (size.width>125) {
                    personCell.genderOrType.frame=CGRectMake(85+125+5, 23, 13, 13);
                }
                else
                {
                    personCell.genderOrType.frame=CGRectMake(85+size.width+5, 23, 13, 13);
                }
            }
            personCell.authorDoc.layer.cornerRadius=2;
            personCell.authorDoc.layer.masksToBounds=YES;
            if ([[NSString stringWithFormat:@"%@",[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"type"]] isEqualToString:@"1"]) {
                
                NSString *gender=[NSString stringWithFormat:@"%@",[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"gender"]];
                personCell.authorDoc.hidden=YES;

                if ([gender isEqualToString:@"0"]) {
                }else if ([gender isEqualToString:@"1"]){
                    personCell.genderOrType.image=[UIImage imageNamed:@"personNearby_men@2x.png"];
                }
                else{
                    personCell.genderOrType.image=[UIImage imageNamed:@"personNearby_women@2x.png"];
                }
                
            }else
            {
                personCell.genderOrType.image=[UIImage imageNamed:@"personNearby_doc@2x.png"];
                personCell.authorDoc.hidden=NO;
            }
//            personCell.otherLabel.text=[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"bio"];
            personCell.distanceLabel.text=[NSString stringWithFormat:@"%@",[[self.personNearbyArray objectAtIndex:indexPath.row] valueForKey:@"distance"]] ;
            personCell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        cell=personCell;

    }else if ([tableView isEqual:self.nearHospital])
    {
        static NSString *CellIdentifie = @"EncyHospitalCell";
        EncyHospitalCell *encyHospitalCell = (EncyHospitalCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifie];
        
        if (!encyHospitalCell) {
            if (kScreenWidth==414) {
                encyHospitalCell = [[[NSBundle mainBundle] loadNibNamed:@"EncyHospitalCell" owner:self options:nil] lastObject];
            }else{
                encyHospitalCell = [[[NSBundle mainBundle] loadNibNamed:@"EncyHospitalCell" owner:self options:nil] objectAtIndex:0];
            }
        }
        
        if (self.hospitalNearbyArray.count>0) {
            encyHospitalCell.encyHospitalNameLab1.text = TextString ([[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"hospitalname"]);
            encyHospitalCell.encyHospitalAddressLab.text = TextString([[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"address"]);
            encyHospitalCell.encyHospitalLevelLab.text = TextString([[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"levelname"]);
            encyHospitalCell.distanceLabel.text=TextString([[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"distance"]);
            
            if ([[[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"pic"] integerValue] == 0) {
                
            }else if ([[[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"pic"] integerValue] == 1){
                
                [encyHospitalCell.encyHospitalImageView setImageWithURL:[NSURL URLWithString:[[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"picurl"]]placeholderImage:[UIImage imageNamed:@"hos-l.png"]];
            }
            
                encyHospitalCell.encyHospitalImageView.layer.cornerRadius = 3;
                encyHospitalCell.encyHospitalImageView.layer.masksToBounds = YES;
            
            NSString *bad=[NSString stringWithFormat:@"%@",[[self.hospitalNearbyArray objectAtIndex:indexPath.row] valueForKey:@"isbad"]];
            if ([bad isEqualToString:@"0"]) {
                encyHospitalCell.isBadImageView.hidden=YES;
            }else
            {
                encyHospitalCell.isBadImageView.hidden=NO;
            }

        }
        encyHospitalCell.selectionStyle=UITableViewCellSelectionStyleNone;

        cell= encyHospitalCell;
    }
    else
    {
        static NSString *CellIdentifier = @"DrugNearStoreCell";
        DrugNearStoreCell *drugNearStoreCell = (DrugNearStoreCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!drugNearStoreCell) {
            if (kScreenWidth==414) {
                drugNearStoreCell = [[[NSBundle mainBundle] loadNibNamed:@"DrugNearStoreCell" owner:self options:nil] lastObject];
            }
            else{
                drugNearStoreCell = [[[NSBundle mainBundle] loadNibNamed:@"DrugNearStoreCell" owner:self options:nil] objectAtIndex:0];

            }
            
        }
        if ([self.storeNearbyArray count]>0) {
            drugNearStoreCell.drugNearStoreNameLab.text = TextString([[self.storeNearbyArray objectAtIndex:indexPath.row] valueForKey:@"name"]);
            drugNearStoreCell.drugNearStoreLocationLab.text = TextString([[self.storeNearbyArray objectAtIndex:indexPath.row] valueForKey:@"address"]);
            drugNearStoreCell.drugNearStoreDicLab.text = [NSString stringWithFormat:@"%@米",[[self.storeNearbyArray objectAtIndex:indexPath.row] valueForKey:@"distance"]];
//            [drugNearStoreCell.drugNearStoreTelBtn setTag:indexPath.row];
//            NSLog(@"ww=%d",indexPath.row);
            drugNearStoreCell.index=indexPath.row;

            drugNearStoreCell.callDelegate=self;
            if ([[[self.storeNearbyArray objectAtIndex:indexPath.row] valueForKey:@"tel"] length] > 0) {
                drugNearStoreCell.drugNearStoreTelBtn.enabled = YES;
                [drugNearStoreCell.drugNearStoreTelBtn setImage:[UIImage imageNamed:@"phoneyes.png"] forState:UIControlStateNormal];
                //drugNearStoreCell.drugNearStoreTelBtn.tag=indexPath.row;
                //[drugNearStoreCell.drugNearStoreTelBtn addTarget:self action:@selector(callActions:) forControlEvents:UIControlEventTouchUpInside];
            } else {
                //change
                [drugNearStoreCell.drugNearStoreTelBtn setImage:[UIImage imageNamed:@"phoneno.png"] forState:UIControlStateNormal];
//                [drugNearStoreCell.drugNearStoreTelBtn addTarget:self action:@selector(callAction1:) forControlEvents:UIControlEventTouchUpInside];
                
            }
            
            drugNearStoreCell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        cell= drugNearStoreCell;

    }
    return cell;
}

- (void)backClicked
{
    self.mapview.delegate=nil;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma  mark
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.nearPersonTableview]) {
        if (kScreenWidth==414) {
            return 82;
        }
        return 64.f;
    }
    else if ([tableView isEqual:self.nearStore])
    {
        if (kScreenWidth==414) {
            return 108;
        }
        return 90;
    }
    else {
        if (kScreenWidth==414) {
            return 73;
        }
       return 60;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.nearPersonTableview]) {
        NSDictionary *dic=[self.personNearbyArray objectAtIndex:indexPath.row];
        if ([[NSString stringWithFormat:@"%@",[dic valueForKey:@"type"]] isEqualToString:@"2"]) {
            DocInfoViewController *docInfo=[[DocInfoViewController alloc]initWithNibName:@"DocInfoViewController" bundle:[NSBundle mainBundle]];
            
            docInfo.doctoruid=[dic valueForKey:@"uid"];
            [self.navigationController pushViewController:docInfo animated:YES];
        }
        else
        {
            FirendDetailViewController *friend=[[FirendDetailViewController alloc]initWithNibName:@"FirendDetailViewController" bundle:[NSBundle mainBundle]];
            friend.firendId=[dic valueForKey:@"uid"];
            [self.navigationController pushViewController:friend animated:YES];
        }
        
    }else if ([tableView isEqual:self.nearHospital])
    {
        NearbyPathViewController *path=[[NearbyPathViewController alloc]init];
        path.destinationDic=[self.hospitalNearbyArray objectAtIndex:indexPath.row];
        path.lattited=[self.latitude floatValue];
        path.lngtited=[self.longitude floatValue ];
        path.cityName=cityName;
        path.isFromStore=NO;
        path.isFromHosp=NO;

        [self.navigationController pushViewController:path animated:YES];
    }
    else
    {
        NearbyPathViewController *path=[[NearbyPathViewController alloc]init];
        path.p=[self.storeNearbyArray objectAtIndex:indexPath.row];
//        path.lat=[self.latitude floatValue];
//        path.lng=[self.longitude floatValue ];

        path.cityName=cityName;
        path.isFromStore=YES;
        path.isFromHosp=NO;

        [self.navigationController pushViewController:path animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma  mark ------- 点击附近的人、医院、药店
- (IBAction)nearPersonClick:(id)sender {
    
    
    indexSelected=0;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButtonMore];
    
    self.mapview.hidden=YES;
    
    [self.perseonSender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal ];
    [self.hospitalSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];
    [self.storeSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];

    
    self.personLine.backgroundColor=[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.hospLine.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.storeLine.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    if (self.personNearbyArray.count>0) {
        self.nearPersonTableview.hidden=NO;
    }else
    {
        CLAuthorizationStatus status=[CLLocationManager authorizationStatus];
        if (status==kCLAuthorizationStatusDenied||kCLAuthorizationStatusRestricted==status) {
            [self showCustomHudSingleLine:@"你必须允许“安好”来确定你的位置."];
        }else
        {
            if (success!=YES) {
                return ;
            }
            [self postUserLatAndLongtude];
        }
    }
    self.nearHospital.hidden=YES;
    self.nearStore.hidden=YES;
    
}
- (IBAction)nearHospitalClick:(id)sender {
    
    
    indexSelected=1;
    [self.mapview removeAnnotations:flagStoreArray];
    CLLocationCoordinate2D coor;
    coor.latitude= [self.latitude floatValue]  ;
    coor.longitude =[self.longitude floatValue];
    
    MACoordinateSpan span = MACoordinateSpanMake(0.1, 0.1);
    MACoordinateRegion region = MACoordinateRegionMake(coor, span);
    [self.mapview setRegion:region animated:YES];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:hosrightButton];
    if (showHosList) {
        self.mapview.hidden=YES;
        self.nearHospital.hidden=NO;
    }
    else
    {
        self.nearHospital.hidden=YES;
        self.mapview.hidden=NO;
    }
    self.hospLine.backgroundColor=[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.personLine.backgroundColor=[ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    self.storeLine.backgroundColor=[ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    
    [self.perseonSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];
    [self.hospitalSender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal ];
    [self.storeSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];
    self.nearHospital.hidden=NO;
    self.nearPersonTableview.hidden=YES;

    self.nearStore.hidden=YES;
    
    CLAuthorizationStatus status=[CLLocationManager authorizationStatus];
    if (status==kCLAuthorizationStatusDenied||kCLAuthorizationStatusRestricted==status) {
        [self showCustomHudSingleLine:@"你必须允许“安好”来确定你的位置."];
    }
    else
    {
        if (self.hospitalNearbyArray.count>0) {
            [self.mapview addAnnotations:flagHospArray];
        }
        else
        {
            
            if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
                [self showCustomHudSingleLine:@"你必须允许“安好”来确定你的位置."];
                return ;
            }
            if (success!=YES) {
                return ;
            }
            [self loadNearHospitalData];
        }
    }
}
- (IBAction)nearStoreClick:(id)sender {
    indexSelected=2;

    [self.mapview removeAnnotations:flagHospArray];

    
    CLLocationCoordinate2D coor;
    coor.latitude= [self.latitude floatValue]  ;
    coor.longitude =[self.longitude floatValue];
    
    MACoordinateSpan span = MACoordinateSpanMake(0.03, 0.03);
    MACoordinateRegion region = MACoordinateRegionMake(coor, span);
    [self.mapview setRegion:region animated:YES];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:storerightButton];
    if (showStoreList) {
        self.mapview.hidden=YES;
        self.nearStore.hidden=NO;
    }
    else
    {
        self.nearStore.hidden=YES;
        self.mapview.hidden=NO;
    }
    self.storeLine.backgroundColor=[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.hospLine.backgroundColor=[ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    self.personLine.backgroundColor=[ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    
    
    [self.perseonSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];
    [self.hospitalSender setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal ];
    [self.storeSender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal ];
    self.nearStore.hidden=NO;
    self.nearHospital.hidden=YES;
    self.nearPersonTableview.hidden=YES;
    
    CLAuthorizationStatus status=[CLLocationManager authorizationStatus];
    if (status==kCLAuthorizationStatusDenied||kCLAuthorizationStatusRestricted==status) {
        [self showCustomHudSingleLine:@"你必须允许“安好”来确定你的位置."];
    }
    else
    {
        if (self.storeNearbyArray.count>0) {
            [self.mapview addAnnotations:flagStoreArray];
        }
        else
        {
            if (success!=YES) {
                return ;
            }
            [self searchPlaceByAround];
        }
    }
    
}


#pragma  mark    ------------ 搜索附近的医院
/**
 *  请求附近的医院
 */
- (void)loadNearHospitalData
{
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@wiki/nearHospital",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"lat":self.latitude,
                                 @"long":self.longitude,
                                 @"page":[NSString stringWithFormat:@"%ld",self.hosPage+1],
                                 };
    [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            for (int i=0; i<[[responseObject valueForKey:@"data"] count]; i++) {
                CLLocationCoordinate2D coordinate2d;
                CGFloat lat=[[[[responseObject valueForKey:@"data"] objectAtIndex:i]valueForKey:@"lat"] doubleValue];
                CGFloat lng=[[[[responseObject valueForKey:@"data"] objectAtIndex:i] valueForKey:@"lng"] doubleValue];
                coordinate2d = CLLocationCoordinate2DMake(lat, lng);
                MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
                annotation.coordinate = coordinate2d;
                annotation.title = [NSString stringWithFormat:@"%d",i];
                [flagHospArray addObject:annotation];
                [self.hospitalNearbyArray addObject:[[responseObject valueForKey:@"data"] objectAtIndex:i]];
            }
            [self.mapview addAnnotations:flagHospArray];
            [self searchReGeocode];

            [self.nearHospital reloadData];        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
}
#pragma mark  ----搜索附近药店---高德接口
/**
 *  请求周边搜索附近的药店
 */
- (void)searchPlaceByAround
{
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:@"c36674eca6a6cb5e40526f275ed4d241" Delegate:self];
    self.search.delegate = self;
    AMapPlaceSearchRequest *poiRequest = [[AMapPlaceSearchRequest alloc] init];
    poiRequest.searchType = AMapSearchType_PlaceAround;
    AMapGeoPoint *amapGeo = [AMapGeoPoint locationWithLatitude:[self.latitude floatValue] longitude:[self.longitude floatValue]];
    poiRequest.location = amapGeo;
    poiRequest.keywords = @"药店";
    poiRequest.radius= 3000;
    
    [self.search AMapPlaceSearch:poiRequest];
}
- (void)onPlaceSearchDone:(AMapPlaceSearchRequest *)request response:(AMapPlaceSearchResponse *)response
{
    int tt = 0;
    for (p in response.pois) {
        tolocation.longitude = p.location.longitude;
        tolocation.latitude = p.location.latitude;
        
        [self.storeNearbyArray addObject:p];
        [storeTelArray addObject:p.tel];
        //添加大头针
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = tolocation;
        annotation.title = [NSString stringWithFormat:@"%d",tt];
        tt++;
        [flagStoreArray addObject:annotation];
    }
    [self searchReGeocode];
    [self.mapview addAnnotations:flagStoreArray];

    [self.nearStore reloadData];
}
#pragma  mark ------逆地理编码
/**
 *  逆地理编码描述
 */
- (void)searchReGeocode
{
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:@"c36674eca6a6cb5e40526f275ed4d241" Delegate:self];
    self.search.delegate = self;
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.searchType = AMapSearchType_ReGeocode;
    regeoRequest.location= [AMapGeoPoint locationWithLatitude:[self.latitude floatValue] longitude:[self.longitude floatValue]];
    //+0.001246  +0.006045
    regeoRequest.radius = 1000;
    regeoRequest.requireExtension = YES;
    [self.search AMapReGoecodeSearch: regeoRequest];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    cityName=[[response.regeocode valueForKey:@"addressComponent"] valueForKey:@"province"];
}

#pragma mark 展示附近的人筛选
/**
 *  附近的人展示筛选
 *
 *  @param sender
 */
- (void)showListView:(UIButton *)sender
{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    NSArray *titles = @[@"查看全部", @"认证医生",@"附近患友",@"清除位置信息并退出"];
    NSArray *images = @[@"附近_全部", @"附近_医生",@"附近_患友",@"附近_清除位置"];
    NSArray *selectArray=@[@"附近_全部成功",@"附近_已认证",@"附近_患友成功",@"附近_清除位置成功"];
    pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectArray];
    pop.selectRowAtIndex = ^(NSInteger index){
        MyNSLog("select index:%d", index);
        switch (index) {
            case 0:
            {
                [self.personNearbyArray removeAllObjects];
                MyNSLog("第一个");
                self.personNearbyArray=[NSMutableArray arrayWithArray:tempArray];
                [self.nearPersonTableview reloadData];
            }
                break;
            case 1:
            {
                [self.personNearbyArray removeAllObjects];
                MyNSLog("第二个");
                for(NSDictionary *dic in tempArray)
                {
                    NSString *type=[NSString stringWithFormat:@"%@",[dic valueForKey:@"type"]];
                    if ([type isEqualToString:@"2"]) {
                        [self.personNearbyArray addObject:dic];
                    }
                }
                [self.nearPersonTableview reloadData];
            }
                break;
            case 2:
            {
                MyNSLog("第三个");
                [self.personNearbyArray removeAllObjects];
                for(NSDictionary *dic in tempArray)
                {
                    NSString *type=[NSString stringWithFormat:@"%@",[dic valueForKey:@"type"]];
                    if ([type isEqualToString:@"1"]) {
                        [self.personNearbyArray addObject:dic];
                    }
                }
                [self.nearPersonTableview reloadData];
            }
                break;
            case 3:
            {
                MyNSLog("第四个");
                [self.personNearbyArray removeAllObjects];
                [self showActionView];
                NSString * postURL = [NSString stringWithFormat:@"%@user/lnglatdel/",kBaseURL];
                AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
                NSDictionary *parameters = @{
                                             @"platform": kPlatform,
                                             @"version":kVersion,
                                             };
                [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSNumber * statusNum = [responseObject objectForKey:@"status"];
                    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                    NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                    [self hiddenActionView];
                    if ([statusString isEqualToString:@"0"]) {
                    }else{
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    [self hiddenActionView];
                }];
                
            }
                break;
                default:
                break;
        }
    };
    [pop show];
}
/**
 *  显示列表或者地图
 *
 *  @param sender
 */
- (void)rightButtonAddCircleClicked:(UIButton *)sender
{
    if(sender.tag==10)
    {
        if (showHosList) {
            showHosList=NO;
            [hosrightButton setTitle:@"列表" forState:UIControlStateNormal];
            self.mapview.hidden=NO;

        }else
        {
            [hosrightButton setTitle:@"地图" forState:UIControlStateNormal];
            showHosList=YES;
            self.mapview.hidden=YES;
        }
    }
    else if (sender.tag==11)
    {
        if (showStoreList) {
            [storerightButton setTitle:@"列表" forState:UIControlStateNormal];
            showStoreList=NO;
            self.mapview.hidden=NO;
        }else
        {
            showStoreList=YES;
            [storerightButton setTitle:@"地图" forState:UIControlStateNormal];
            self.mapview.hidden=YES;
        }
    }
}
- (CGSize)autolayoutText:(NSString *)text WithTextLabel:(UILabel *)textlabel WithWidth:(CGFloat )width
{
    
    CGSize size =CGSizeMake(width,0);
    textlabel.lineBreakMode=NSLineBreakByCharWrapping;
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:textlabel.font,NSFontAttributeName,nil];
    CGSize  actualsize;
    actualsize =[textlabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
    return actualsize;
}
#pragma  mark  插入大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
            annotationView.cusdelegate=self;
        }
        annotationView.portrait = [UIImage imageNamed:@"nearbyDrug_markUnselect@2x.png"];
        return annotationView;
    }
    return nil;
}
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    if (indexSelected==0) {
    }
    else if (indexSelected==1)
    {
        CGFloat lat= [[[self.hospitalNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"lat"] doubleValue];
        CGFloat lng=[[[self.hospitalNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"lng"] doubleValue];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
        [mapView setCenterCoordinate:coordinate animated:YES];
        if ([view isKindOfClass:[CustomAnnotationView class]]) {
            CustomAnnotationView *cusView = (CustomAnnotationView *)view;
            cusView.portraitImageView.frame=CGRectMake(-5, 0, 23, 31);
            cusView.tag=[view.annotation.title integerValue];
            cusView.itemName.text=[[self.hospitalNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"hospitalname"];
            
            if ([[[self.hospitalNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"phone"]length]>0) {
                NSString *regexString  = @"(\\d{11})|(\\d{3}-\\d{3}-\\d{4})|(\\d{3,4}-\\d{7,8}|(\\d{7,8}))";
                NSString *tel=[[self.hospitalNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"phone"];
                NSArray  *matchArray  = [tel componentsMatchedByRegex:regexString];
                telArray=matchArray;
                cusView.tel.text=[matchArray objectAtIndex:0];
            }else{
                cusView.telGo.userInteractionEnabled=NO;
                cusView.tel.text=@"暂无";
            }
        }
    }
    else if (indexSelected==2)
    {
        AMapGeoPoint *point = [[self.storeNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"location"];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude);
        [mapView setCenterCoordinate:coordinate animated:YES];
        
        if ([view isKindOfClass:[CustomAnnotationView class]]) {
            CustomAnnotationView *cusView = (CustomAnnotationView *)view;
            cusView.portraitImageView.frame=CGRectMake(-5, 0, 23, 31);
            cusView.tag=[view.annotation.title integerValue];
            
            cusView.itemName.text=[[self.storeNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"name"];
            
            if ([[[self.storeNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"tel"]length]>0) {
                        NSString *regexString  = @"(\\d{11})|(\\d{3}-\\d{3}-\\d{4})|(\\d{3,4}-\\d{7,8}|(\\d{7,8}))";
                        NSArray  *matchArray  = [[[self.storeNearbyArray objectAtIndex:[view.annotation.title integerValue]]valueForKey:@"tel"] componentsMatchedByRegex:regexString];
                        telArray=matchArray;
                        cusView.tel.text=[matchArray objectAtIndex:0];
                }else{
                        cusView.tel.text=@"暂无电话";
                        cusView.telGo.userInteractionEnabled=NO;
                }
        }

    }
}
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    if ([view isKindOfClass:[CustomAnnotationView class]]) {
        CustomAnnotationView *cusView = (CustomAnnotationView *)view;
        cusView.portraitImageView.frame=CGRectMake(0, 0, 14, 19);
        cusView.portrait = [UIImage imageNamed:@"nearbyDrug_markUnselect@2x.png"];
    }
}
#pragma mark------------customannotationviewdelegate
//打电话或导航所执行的代理方法
- (void)clickGPSWithLat:(NSString *)lat WithLong:(NSString *)lng WithTag:(NSInteger)tag
{
    //数据保护，必须有用户的经纬度。否则进入下一个界面崩溃
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"你必须启用定位服务,打开定位服务允许“安好”来确定你的位置." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alert show];
        [self showCustomHudSingleLine:@"您必须允许“安好”来确定您的位置."];
        return ;
    }
    if (indexSelected==1) {
        NearbyPathViewController *path=[[NearbyPathViewController alloc]init];
        path.destinationDic=[self.hospitalNearbyArray objectAtIndex:tag];
        path.cityName=cityName;
        path.isFromStore=NO;
        path.isFromHosp=NO;
        path.lat=[self.latitude floatValue];
        path.lng=[self.longitude floatValue];
        [self.navigationController pushViewController:path animated:YES];
    }
    else if (indexSelected==2)
    {
        NearbyPathViewController *path=[[NearbyPathViewController alloc]init];
        path.p=[self.storeNearbyArray objectAtIndex:tag];
        path.cityName=cityName;
        path.isFromStore=YES;
        path.isFromHosp=NO;
//        path.lat=[self.latitude floatValue];
//        path.lng=[self.longitude floatValue];
        [self.navigationController pushViewController:path animated:YES];

    }
}
- (void)clickTelWithTag:(NSInteger)tag
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    for ( int i=0; i<[telArray count]; i++) {
        [actionSheet addButtonWithTitle:[telArray objectAtIndex:i]];
    }
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet addButtonWithTitle:@"取消"];
    actionSheet.cancelButtonIndex=actionSheet.numberOfButtons-1;
    
    
    [actionSheet showInView:[[[UIApplication sharedApplication]delegate] window]];

}
- (void)clickDetail:(NSInteger)tag
{
    if (indexSelected==1) {
        NSDictionary *dic = [self.hospitalNearbyArray objectAtIndex:tag];
        DoctorDetailViewController *encyHDVC = [[DoctorDetailViewController alloc] init];
        
//        encyHDVC.hosp_lat=encyHospitalModel.latitude;
//        encyHDVC.hosp_lng=encyHospitalModel.longitude;
//        encyHDVC.titleLabel.text = TextString(encyHospitalModel.hospitalname);
//        encyHDVC.hosTitle=encyHospitalModel.hospitalname;
//        encyHDVC.encyHDInfo = TextString(encyHospitalModel.hospitalid);
        encyHDVC.diseaseid=[NSString stringWithFormat:@"%@",[dic valueForKey:@"hospitalid"]];
        [self.navigationController pushViewController:encyHDVC animated:YES];
    }
    else if (indexSelected==2)
    {
    }
    
}
- (void)callActionTel:(NSInteger)index
{
    int row = index;
    NSMutableArray *itemArray=[[NSMutableArray alloc]init];
    
    if ([[[self.storeNearbyArray objectAtIndex:row] valueForKey:@"tel"] isEqualToString:@""]) {
    } else{
        
        NSString *tel = [[self.storeNearbyArray objectAtIndex:row] valueForKey:@"tel"];
        if ([tel rangeOfString:@";"].length>0) {
            itemArray=[NSMutableArray arrayWithArray:[tel componentsSeparatedByString:@";"]];
        }
        else
        {
            [itemArray addObject:tel];
        }
    }
    
    
    if (itemArray.count>0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        for ( int i=0; i<[itemArray count]; i++) {
            [actionSheet addButtonWithTitle:[itemArray objectAtIndex:i]];
        }
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        
        [actionSheet addButtonWithTitle:@"取消"];
        actionSheet.cancelButtonIndex=actionSheet.numberOfButtons-1;
        [actionSheet showInView:self.view];
    }

}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == [actionSheet cancelButtonIndex]) {
        return;
    }
    
    
    else {
        NSString *number = [telArray objectAtIndex:buttonIndex];
        NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",number];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
    }
}

@end
